package com.dongjiantong.web.protal.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsDicGroupEnum;
import com.dongjiantong.farmrecords.service.FarmRecordsHarmlessesService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.enums.HarmlessFormsType;
import com.dongjiantong.quarantine.enums.HarmlessStatus;
import com.dongjiantong.quarantine.model.Harmless;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.HarmlessReadService;
import com.dongjiantong.sys.model.DicData;
import com.dongjiantong.sys.service.DicDataService;
import com.dongjiantong.user.model.Farms;
import com.dongjiantong.user.service.FarmsService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by mz on 9/1/18.
 */
@Slf4j
@OpenBean
public class HarmlessWebController {

    private final static SimpleDateFormat DFT = new SimpleDateFormat("yy-MM-dd");

    @Reference(version = "1.0.0")
    private HarmlessReadService harmlessReadService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;

    @Reference(version = "1.0.0")
    private FarmsService farmsService;

    @Reference(version = "1.0.0")
    private FarmRecordsHarmlessesService farmRecordsHarmlessesService;

    @Reference(version = "1.0.0")
    public DicDataService dicDataService;

    @OpenMethod(
            key = "web.paging.harmless",
            paramNames = {"pageNum", "pageSize", "startDate", "endDate", "areaList", "breedType", "treatment"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<Harmless>> pagingHarmlessForWeb(Integer pageNum,
                                                             Integer pageSize,
                                                             String startDate,
                                                             String endDate,
                                                             List<Integer> areaList,
                                                             List<Integer> breedType,
                                                             String treatment) {

        try {
            List<Long> farmIds = new ArrayList<>();
            farmIds.add(-1L);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Farms> farms = farmsService.selectByUserId(loginInfo.getId());
            for (Farms farm : farms) farmIds.add(farm.getId());

            Map<String, Object> map = Maps.newHashMap();
            map.put("farmIds", farmIds);
            int i = 0;
            for (Integer areaCode : areaList) {
                if (i == 0) {
                    map.put("province_id", areaCode);
                } else if (i == 1) {
                    map.put("city_id", areaCode);
                } else if (i == 2) {
                    map.put("region_id", areaCode);
                } else if (i == 3) {
                    map.put("street_id", areaCode);
                }
                i++;
            }
            if (!Strings.isNullOrEmpty(startDate)) {
                Date startDate1 = new Date(Long.valueOf(startDate));
                map.put("start", startDate1);
            }
            if (!Strings.isNullOrEmpty(endDate)) {
                Date endDate1 = new Date(Long.valueOf(endDate) + 86400000);
                map.put("end", endDate1);
            }
            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        map.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        map.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        map.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            }
            if (!Strings.isNullOrEmpty(treatment)) {
                map.put("treatment", Integer.parseInt(treatment));
            }
            map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
            map.put("deleteFlag", 1);
            PageInfo<Harmless> harmlessPageInfo = harmlessReadService.pagingForGov(pageNum, pageSize, map);
            for (Harmless harmless : harmlessPageInfo.getList()) {
                map.clear();
                map.put("field", "harmless_photos");
                map.put("type1", ReportType.HARMLESS.value());
                map.put("type2", 1);
                map.put("relevanceId", harmless.getId());
                List<String> harmless_photos = breedReportsFileReadService.findListByType(map);
                map.put("field", "harmless_videos");
                map.put("type2", 2);
                List<String> harmless_videos = breedReportsFileReadService.findListByType(map);
                map.put("field", "harmless_video_snapshoots");
                map.put("type2", 1);
                List<String> harmless_video_snapshoots = breedReportsFileReadService.findListByType(map);
                map.clear();
                map.put("reportId", harmless.getId());
                map.put("reportType", ReportType.HARMLESS.value());
                List<String> earTagNumbers = earMarkLifeReadeService.findListByBreedReportId(map);
                harmless.setHarmless_photos(harmless_photos);
                harmless.setHarmless_videos(harmless_videos);
                harmless.setHarmless_video_snapshoots(harmless_video_snapshoots);
                harmless.setEar_tag_numbers(earTagNumbers);
            }
            return Response.ok(harmlessPageInfo);
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    @OpenMethod(
            key = "web.get.a.week.harmless.by.report.type",
            paramNames = {"breedType"},
            httpMethods = RequestMethod.GET
    )
    public Response<Map<Integer, List>> getAWeekHarmlessByReportType(List<Integer> breedType) {

        try {
            Map<Integer, List> result = Maps.newHashMap();
            Map<String, Object> paramsMap = Maps.newHashMap();
            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        paramsMap.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        paramsMap.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        paramsMap.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            } else {
                paramsMap.put("breedSecondType", 101);
            }

            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Map<String, Object> paramForFarm = Maps.newHashMap();
            paramForFarm.put("userId", loginInfo.getId());
            List<Farms> farms = farmsService.selectByMap(paramForFarm);
            List<Long> farmIds = new ArrayList<>();
            for (Farms farm : farms) farmIds.add(farm.getId());

            paramsMap.put("farmIds", farmIds);
            paramsMap.put("status", HarmlessStatus.FINISHED.value());
            paramsMap.put("reportType", ReportType.ADMISSION_INSPECTION.value());
            List<Map<String, Object>> isLocals = harmlessReadService.findAWeekSumIsLocal(paramsMap);
            List<Map<String, Object>> sumReportTypes = harmlessReadService.findAWeekSumReportType(paramsMap);
            paramsMap.put("status", 1);
            List<Map<String, Object>> farmRecordHarmless = farmRecordsHarmlessesService.findAWeekSum(paramsMap);


            List<Map<String, Object>> maps1 = new ArrayList<>();//产地检疫
            List<Map<String, Object>> maps2 = new ArrayList<>();//外市入场
            List<Map<String, Object>> maps3 = new ArrayList<>();//本市入场
            List<Map<String, Object>> maps4 = new ArrayList<>();//宰前检查
            List<Map<String, Object>> maps5 = new ArrayList<>();//同步检疫
            List<Map<String, Object>> maps6 = new ArrayList<>();//防疫中心
            for (Map<String, Object> map : isLocals) {
                if ((int) map.get("isLocal") == -1) {
                    maps2.add(map);
                } else {
                    maps3.add(map);
                }
            }
            for (Map<String, Object> map : sumReportTypes) {
                switch ((int) map.get("reportType")) {
                    case 1:
                        maps1.add(map);
                        break;
                    case 5:
                        maps4.add(map);
                        break;
                    case 6:
                        maps5.add(map);
                        break;
                    default:
                        break;
                }
            }
            maps1 = make(maps1);
            maps2 = make(maps2);
            maps3 = make(maps3);
            maps4 = make(maps4);
            maps5 = make(maps5);
            maps6 = make(farmRecordHarmless);
            result.put(HarmlessFormsType.QUARANTINE_ORIGIN_AREA.value(), maps1);
            result.put(HarmlessFormsType.ADMISSION_INSPECTION_NON_LOCAL.value(), maps2);
            result.put(HarmlessFormsType.ADMISSION_INSPECTION_LOCAL.value(), maps3);
            result.put(HarmlessFormsType.ANTEMORTEM_INSPECTION.value(), maps4);
            result.put(HarmlessFormsType.SYNCHRONOUS_INSPECTION.value(), maps5);
            result.put(HarmlessFormsType.QUARANTINE_CENTER_HARMLESS.value(), maps6);
            return Response.ok(result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @OpenMethod(
            key = "web.get.a.week.harmless.by.treatment",
            paramNames = {"breedType"},
            httpMethods = RequestMethod.GET
    )
    public Response<Map<String ,List>> getAWeekHarmlessByTreatment(List<Integer> breedType) {
        try {
            Map<String, Object> paramsMap = Maps.newHashMap();
            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        paramsMap.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        paramsMap.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        paramsMap.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            } else {
                paramsMap.put("breedSecondType", 101);
            }

            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Map<String, Object> paramForFarm = Maps.newHashMap();
            paramForFarm.put("userId", loginInfo.getId());
            List<Farms> farms = farmsService.selectByMap(paramForFarm);
            List<Long> farmIds = new ArrayList<>();
            for (Farms farm : farms) farmIds.add(farm.getId());

            paramsMap.put("farmIds", farmIds);
            paramsMap.put("status", HarmlessStatus.FINISHED.value());
            List<DicData> list = dicDataService.queryDicByGroup(FarmRecordsDicGroupEnum.HARMLESSES_TYPE.getDicCode());
            List<Map<String, Object>> preResult = harmlessReadService.getAWeekHarmlessByTreatment(paramsMap);

            Map<String , List<Map<String , Object>>> result = Maps.newHashMap();

            for (DicData dicData : list) {
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (Map<String, Object> map : preResult) {
                    if ((int) map.getOrDefault("treatment", 0) == Integer.parseInt(dicData.getDicValue())) {
                        mapList.add(map);
                    }
                }
                result.put(dicData.getDicName(),make(mapList));
            }

            Map<String , List> result1 = Maps.newHashMap();
            List<Object> dateList = new ArrayList<>();
            List<Map<String , Object>> dataList = new ArrayList<>();
            List<Object> labelList = new ArrayList<>();
            for(DicData dicData : list){
                labelList.add(dicData.getDicName());
                List<Object> list1 = new ArrayList<>();
                Map<String , Object> map1 = Maps.newHashMap();
                map1.put("name",dicData.getDicName());
                map1.put("type","line");

                for(Map<String , Object> map : result.get(dicData.getDicName())){
                    dateList.add(map.getOrDefault("date",""));
                    list1.add(map.getOrDefault("quantity",0));
                }
                map1.put("data",list1);
                dataList.add(map1);
            }
            result1.put("label",labelList);
            result1.put("data",dataList);
            result1.put("date",dateList.subList(0,7));
            return Response.ok(result1);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    private List<Map<String, Object>> make(List<Map<String, Object>> list) throws ParseException {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Calendar[] calendars = new Calendar[7];
        Map<String, Object> temp = null;

        for (int i = 0; i < 7; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - i);
            calendars[i] = calendar;
            temp = Maps.newHashMap();
            temp.put("date", DFT.format(calendar.getTime()));
            temp.put("quantity", 0);
            mapList.add(temp);
        }
        if (list == null || list.size() == 0) {
            return mapList;
        } else {
            for (Map<String, Object> map : list) {
                Calendar calendarTemp = Calendar.getInstance();
                Date date = DFT.parse(map.get("date").toString());
                calendarTemp.setTime(date);
                for (int i = 0; i < 7; i++) {
                    if (calendarTemp.equals(calendars[i])) {
                        Map<String, Object> mapTemp = Maps.newHashMap();
                        mapTemp.put("date", map.get("date"));
                        mapTemp.put("quantity", map.get("quantity"));
                        mapList.set(i, mapTemp);
                    }
                }
            }
            return mapList;
        }
    }
}
